<template>
  <div id="roleOperation">
    <div class="pageMain">
      <el-form :model="roleOperationParams" :rules="rules" ref="roleOperationParams" label-width="100px" class="roleOperationParams" :disabled="isEdit ? false : true">
        <div class="formHead" style="font-weight: 600">{{ nameType == "isAddJump" ? "角色添加" : nameType == "isClone" ? "角色克隆" : "角色修改" }}</div>
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="roleOperationParams.roleName" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="备注信息：" prop="remarks">
          <el-input type="textarea" v-model="roleOperationParams.remarks" style="width: 444px"></el-input>
        </el-form-item>
      </el-form>
      <div class="Jurisdiction">
        <div class="formHead">
          <span class="title">权限设置</span>
          <span class="tabs">
            <span :class="actionSetting == 1 ? 'tab active' : 'tab'" @click="actionSetting = 1">功能权限</span>
            <el-divider direction="vertical"></el-divider>
            <span :class="actionSetting == 2 ? 'tab active' : 'tab'" @click="actionSetting = 2">数据权限</span>
          </span>
          <span class="collpae">
            <span v-if="!collpae1" @click="collpae1 = true"><i class="el-icon-caret-bottom"></i>展开</span>
            <span v-if="collpae1" @click="collpae1 = false"><i class="el-icon-caret-top"></i>收起</span>
          </span>
        </div>
        <el-collapse-transition>
          <div class="treeContent" v-show="collpae1" v-loading="authorityLoad">
            <!-- <el-tabs v-model="actionSetting">
            <el-tab-pane label="功能权限" name="1"></el-tab-pane>
            <el-tab-pane label="数据权限" name="2" v-if="userInfo.isPurchase"></el-tab-pane>
          </el-tabs> -->
            <!--2020-1-19 | gz | 修改tree -->
            <el-tree ref="JurisdictionTree" v-show="actionSetting == 1" node-key="id" :check-on-click-node="false" :data="treeData" :props="defaultProps" v-loading="treeLoading" :check-strictly="false" :default-checked-keys="defaultCheckedKeys" show-checkbox highlight-current></el-tree>
            <div class="DataPermission" v-show="actionSetting == 2">
              <!-- <div class="formHead">
              <span class="title">进销存数据权限设置</span>
            </div> -->
              <div class="PermissionContent">
                <!--2020-1-19 | gz | 修改tree -->
                <div class="PermissionItem" v-for="item in jurisdictionData" :key="item.id">
                  <p class="Permissiontitle">
                    <el-divider direction="vertical"></el-divider>
                    <span @click="item.isShow = !item.isShow"
                      >{{ item.companyName }}
                      <i class="iconfont" :style="{ transform: item.isShow ? 'rotateZ(180deg)' : '' }">&#xe62d;</i>
                    </span>
                  </p>
                  <div class="Content" v-show="item.isShow">
                    <div style="margin-bottom: 15px">
                      <el-checkbox v-model="item.roleAuthyAmounts.isProcurementCost">禁止查看采购成本</el-checkbox>
                      <br />
                      <el-checkbox style="margin-top: 6px" v-model="item.roleAuthyAmounts.isalesAmount">禁止查看销售收入</el-checkbox>
                    </div>
                    <div class="cangkuAction">
                      <span class="title">仓库数据权限</span>
                      <el-radio-group class="radio" @change="WarehouseChage(item.cangku.checkStaus, item)" v-model="item.cangku.checkStaus">
                        <el-radio :label="1">全部仓库</el-radio>
                        <el-radio :label="2">指定仓库</el-radio>
                      </el-radio-group>
                      <el-select v-model="item.cangku.warehouseIds" multiple collapse-tags :disabled="item.cangku.checkStaus == 1" class="select" placeholder="请选择">
                        <el-option v-for="item in item.cangku.cangkuList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                      </el-select>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-collapse-transition>
      </div>
      <div class="Jurisdiction">
        <div class="formHead">
          <span class="title">企业权限 <span class="hint">企业权限为空时默认查看权限仅为本人</span> </span>
          <span class="collpae">
            <span v-if="!collpae2" @click="collpae2 = true"><i class="el-icon-caret-bottom"></i>展开</span>
            <span v-if="collpae2" @click="collpae2 = false"><i class="el-icon-caret-top"></i>收起</span>
          </span>
        </div>
        <el-collapse-transition>
          <div class="treeContent" v-show="collpae2">
            <!-- 1:当前职员权限;2:多部门权限;3:子公司权限;4:本部门权限 -->
            <el-radio-group v-model="dataAuthType">
              <el-radio :label="3">公司</el-radio>
              <el-radio :label="4">本部门</el-radio>
              <el-radio :label="1">本人</el-radio>
              <el-radio :label="2">多部门</el-radio>
            </el-radio-group>
            <el-tree ref="JurisdictionTree1" v-show="dataAuthType == 3 || dataAuthType == 2" node-key="id" :check-on-click-node="false" :data="dataAuthType == 3 ? Companypermissiontree1 : dataAuthType == 2 ? Companypermissiontree : []" :props="defaultProps1" v-loading="treeLoading1" :check-strictly="false" :default-checked-keys="defaultCheckedKeys1" :render-content="sectionrenderContent" show-checkbox highlight-current></el-tree>
          </div>
        </el-collapse-transition>
      </div>
    </div>
    <div class="pageFooter" v-if="isEdit">
      <el-button size="medium" round @click="cancelSave">取 消</el-button>
      <el-button size="medium" type="primary" round :loading="isConfirmLoading" style="margin-left: 30px" @click="saveRoleChange">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
// import baseUrl from '@/config_jxc/baseUrl'
// import instance from "@/config_jxc/http";
// import axios from "axios";
export default {
  name: "roleOperation",
  data() {
    return {
      actionSetting: 1,
      roleOperationParams: {
        roleName: "",
        remarks: "",
        authorityList: [],
      },
      tableData: [],
      tableLoading: false,
      delStaffParams: {},
      treeData: [],
      treeLoading: false,
      treeLoading1: false,
      isConfirmLoading: false,
      total: "",
      isEdit: true,
      defaultProps: {
        children: "childrenList",
        label: "name",
      },
      defaultProps1: {
        children: "mergeList",
        label: "name",
      },
      defaultCheckedKeys: [], // tree回显
      defaultCheckedKeys1: [], // tree回显
      Companypermissiontree: [], // 公司部门职员权限树
      Companypermissiontree1: [], // 公司权限树
      rules: {
        roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      },
      roleid: null,
      jurisdictionData: [], //进销存数据源权限
      dataAuthType: 1, // 1:当前职员权限;2:多部门权限;3:子公司权限;4:本部门权限
      randomNum: "",
      nameType: null,
      collpae1: true,
      collpae2: true,
      authorityLoad: false,
    };
  },
  computed: {
    ...mapState({
      tagCurrent: (state) => state.tag.tagCurrent,
      PermissionTree: (state) => state.common.PermissionTree,
      userInfo: (state) => state.common.userInfo,
      jxc_token: (state) => state.common.jxc_token,
    }),
  },
  methods: {
    WarehouseChage(value, item) {
      if (value == 1) {
        item.cangku.warehouseIds = [];
      }
    },
    getJurisdiction() {
      this.treeData = JSON.parse(JSON.stringify(this.PermissionTree));
      let kq = this.treeData.find((m) => m.name == "考勤管理");
      let sp = this.treeData.find((m) => m.name == "审批报销");
      if (kq) {
        let kq1 = kq.childrenList.find((m) => m.name == "个人考勤");
        if (kq1) {
          kq1.disabled = true;
          this.defaultCheckedKeys.push(kq1.id);
        }
      }
      if (sp) {
        let sp1 = sp.childrenList.find((m) => m.name == "工作台");
        if (sp1) {
          sp1.disabled = true;
          this.defaultCheckedKeys.push(sp1.id);
        }
      }

      if (this.roleid) {
        // 是否修改 | 克隆
        let params = {
          roleid: this.roleid,
          desktop: false,
        };
        this.authorityLoad = true;
        this.$api.systemManagement
          .GetRoleAuthorityTree(params)
          .then((res) => {
            this.authorityLoad = false;
            // 获取角色拥有的权限
            if (!this.nameType) {
              this.roleOperationParams.roleName = this.$route.query.roleName;
              this.roleOperationParams.remarks = this.$route.query.remarks;
            }
            let resData = res.data.data;
            let defaultKeys = [];
            if (resData && resData.length != 0) {
              resData.map((item) => {
                if (item.isSelect && item.islast) {
                  defaultKeys.push(item.id);
                }
              });
            }
            this.defaultCheckedKeys = defaultKeys;
          })
          .catch(() => {
            this.authorityLoad = false;
          });
      }
    },
    GetRoleAuthorityDataTree() {
      // 获取整个公司权限树
      this.treeLoading1 = true;
      this.$api.systemManagement
        .GetRoleAuthorityDataTree({ roleid: this.roleid })
        .then((res) => {
          this.defaultCheckedKeys1 = [];
          this.Companypermissiontree = this.getmergeListFun(JSON.parse(JSON.stringify(res.data.data)));
          this.Companypermissiontree1 = this.getmergeListFun(JSON.parse(JSON.stringify(res.data.data)), true);
          if (this.nameType == "isAddJump") this.defaultCheckedKeys1 = [];
          this.treeLoading1 = false;
        })
        .catch(() => {
          this.treeLoading1 = false;
        });
    },

    /**
     * resList 权限树
     * iscompany 是否只是公司
     */
    getmergeListFun(resList, iscompany) {
      // 公司 权限树初始化
      resList.map((item) => {
        item.isType = 1;
        item.id = new Date().getTime() + Math.random(1);
        if (item.isSelect) {
          this.defaultCheckedKeys1.push(item.id);
        }
        if (item.departmentList && item.departmentList.length != 0 && !iscompany) {
          this.setdepartmentList(item.departmentList);
        }
        if (item.subList && item.subList.length != 0) {
          this.getmergeListFun(item.subList);
        }
      });
      resList.map((item) => {
        if (item.departmentList && item.departmentList.length != 0 && !iscompany) {
          item.mergeList = item.departmentList;
        } else {
          item.mergeList = [];
        }
        if (item.subList && item.subList.length != 0) {
          item.mergeList = [...item.subList, ...item.mergeList];
        }
      });
      return resList;
    },

    setdepartmentList(resList) {
      // 部门职员数据初始化
      resList.map((item) => {
        item.isType = 2;
        item.id = new Date().getTime() + Math.random(1);
        if (item.isSelect) {
          this.defaultCheckedKeys1.push(item.id);
        }
        if (item.childrenList && item.childrenList.length != 0) {
          this.setdepartmentList(item.childrenList, item.level);
        }
        if (item.userList && item.userList.length != 0) {
          item.userList.map((i) => {
            i.isType = 3;
            i.id = new Date().getTime() + Math.random(1);
            if (i.isSelect) {
              this.defaultCheckedKeys1.push(item.id);
            }
          });
        }
        if (item.userList) {
          item.mergeList = item.userList;
        } else {
          item.mergeList = [];
        }
        if (item.childrenList) {
          item.mergeList = [...item.childrenList, ...item.mergeList];
        }
      });
      return resList;
    },

    sectionrenderContent(h, { data }) {
      // 自定义tree节点
      // isType  1 公司  2 部门  3 职员
      return (
        <span class="sectiontreenode">
          <span class="sectionItem">
            <span>{data.isType == 1 ? data.subName : data.isType == 2 ? data.departmentName : data.userName}</span>
          </span>
        </span>
      );
    },

    saveRoleChange() {
      // 保存
      this.$refs["roleOperationParams"].validate((valid) => {
        if (valid) {
          let selectionArr = this.$refs.JurisdictionTree.getCheckedNodes();
          let halfElectionArr = this.$refs.JurisdictionTree.getHalfCheckedNodes();
          let selectionArr1 = this.$refs.JurisdictionTree1.getCheckedNodes();
          // let halfElectionArr1 = this.$refs.JurisdictionTree1.getHalfCheckedNodes()
          this.roleOperationParams.authorityList = [...selectionArr, ...halfElectionArr];
          let dataRangeList = [...selectionArr1];
          if (!this.roleOperationParams.authorityList || this.roleOperationParams.authorityList.length == 0) {
            this.$message({ message: "未勾选权限设置", type: "warning" });
            return;
          }

          // 校验进销存数据权限
          let isjurisdiction = false;
          if (this.userInfo.isPurchase) {
            for (let index = 0; index < this.jurisdictionData.length; index++) {
              let item = this.jurisdictionData[index];
              if (item.cangku.checkStaus == 2 && (!item.cangku.warehouseIds || item.cangku.warehouseIds.length == 0)) {
                isjurisdiction = true;
                this.$message({ message: item.companyName + " " + "仓库权限需选择指定仓库", type: "warning" });
                break;
              }
            }
          }
          if (isjurisdiction) {
            return false;
          }

          let sqlType = !this.nameType ? 2 : 1;
          let dataRangeParams = [];

          dataRangeList.map((item) => {
            // 企业权限注释  普及版没有企业权限
            let isType = item.isType;
            dataRangeParams.push({
              type: isType == 1 ? 3 : isType == 2 ? 2 : 1,
              dataId: isType == 1 ? item.subid : isType == 2 ? item.departmentid : item.userid,
              companyid: item.companyid,
              roleid: sqlType == 2 ? this.roleid : null,
              subId: item.subid,
            });
          });

          this.roleOperationParams.dataRangeList = dataRangeParams;

          let params = {
            ...this.roleOperationParams,
            dataAuthType: this.dataAuthType,
          };
          if (sqlType == 2) {
            params.roleid = this.roleid;
            params.id = Number(this.$route.query.id);
          }

          this.isConfirmLoading = true;
          this.$api.systemManagement
            .GetItemEdit(params, sqlType)
            .then((res) => {
              if (res.data.status == 200) {
                this.$notify({ title: "成功", message: sqlType == 2 ? "修改角色成功" : "添加新角色成功", type: "success", duration: 1500 });
                this.$store.commit("DEL_TAG", this.tagCurrent);
                this.$router.replace({ name: "roleManagement", query: { isGetData: true } });
              } else {
                // this.$message({ message: res.data.message, type: 'warning' })
              }
              this.isConfirmLoading = false;
              this.setAddDataPermission(res.data.data.roleid); // 保存进销存数据权限
            })
            .catch(() => {
              this.isConfirmLoading = false;
            });
        }
      });
    },

    cancelSave() {
      this.$store.commit("DEL_TAG", this.tagCurrent);
      this.$router.replace({ name: "roleManagement" });
    },

    setAddDataPermission(roleid) {
      let params = {
        roleid: this.roleid || roleid,
        // remark:this.roleOperationParams.remarks,
        permissionViews: this.jurisdictionData,
        companyId: this.userInfo.companyid,
      };

      this.$api.jurisdiction.setAddDataPermission(params).then(() => {});
    },

    getDataTreeView() {
      // 进销存数据权限
      this.$api.jurisdiction.getDataTreeView({ roleid: this.roleid, CompanyId: this.userInfo.CompanyId }).then((res) => {
        if (res.data.status == 200) {
          res.data.data.map((item) => {
            item.isShow = false;
          });
          this.jurisdictionData = res.data.data;
        }
      });
    },

    getisPurchase() {
      if (this.userInfo.isPurchase == false) {
        return false;
      } // 是否开通进销存
      this.getDataTreeView();
    },

    initialize() {
      this.nameType = this.$route.query.type ? this.$route.query.type : null;
      this.roleid = this.$route.query.roleid ? this.$route.query.roleid : null;
      this.dataAuthType = this.$route.query.dataAuthType ? this.$route.query.dataAuthType : 1;
      this.GetRoleAuthorityDataTree(); // 企业权限注释
      this.getisPurchase();
      this.getJurisdiction(); // 角色权限反填
    },
  },
  created() {},
  activated() {
    if (this.$route.query.randomNum) {
      if (this.randomNum == "") {
        // 第一次创建
        this.randomNum = this.$route.query.randomNum;
        this.initialize();
      } else if (this.randomNum == this.$route.query.randomNum) {
        // 仅仅是切换过来
        return false;
      } else if (this.randomNum !== this.$route.query.randomNum) {
        // 又进行了其他操作
        this.randomNum = this.$route.query.randomNum;
        this.initialize();
      }
    } else {
      return;
    }
  },
};
</script>

<style lang="less">
#roleOperation {
  overflow: auto;
  padding: 0;
  .pageMain {
    overflow-x: hidden;
    padding: 15px 15px 0 15px;
    margin-top: 0;
    height: calc(100% - 62px) !important;
    .Jurisdiction {
      width: 100%;
      float: left;
      .treeContent {
        width: 100%;
        display: inline-block;
        float: left;
        // font-size: 14px;
        margin-bottom: 8px;
        font-size: 12px !important;
        color: #333333;
        // .el-radio-group {
        //   margin-bottom: 10px;
        // }
        .el-tree {
          .el-tree-node__content {
            .el-tree-node__label {
              font-size: 12px;
              color: #333333;
            }
          }
        }
      }
    }
  }
  .el-form {
    .el-input {
      width: 200px;
    }
  }
  .pageFooter {
    float: left;
    height: 60px;
    line-height: 60px;
    border-top: 1px solid #edecf6;
    width: 100%;
    text-align: center;
    background: #fff;
    z-index: 2;
  }
  .formHead {
    // margin-bottom: 15px;
    .title {
      display: inline-block;
      font-weight: 600;
      // width: 50%;
      margin-right: 30px;

      .hint {
        font-size: 13px;
        color: #999999;
      }
    }
    .tabs {
      .tab {
        font-size: 13px;
        color: #666666;
        cursor: pointer;
      }
      .el-divider {
        background-color: #b7b7b7;
      }
      .active {
        color: #39a4ef;
      }
      .tab:hover {
        color: #39a4ef;
      }
    }
    .collpae {
      float: right;
      font-size: 12px;
      color: #999999;
      cursor: pointer;
      margin-top: 5px;
    }
    .collpae:hover {
      color: #39a4ef;
    }
  }
  .DataPermission {
    // 进销存数据权限
    width: 100%;
    float: left;
    // margin-top: 20px;
    // .formHead {
    //   margin-bottom: 10px;
    // }
    .PermissionContent {
      width: 100%;
      padding: 0 10px 0 0px;
      .PermissionItem {
        margin-bottom: 10px;
        .Permissiontitle {
          display: flex;
          align-items: center;
          height: 40px;
          line-height: 40px;
          padding-left: 10px;
          font-size: 14px;
          color: #333;
          cursor: pointer;
          // border-bottom: 1.5px solid #edecf6;
          font-weight: 600;
          color: #666666;
          .el-divider {
            background-color: #39a4ef;
            width: 3px;
          }
        }
        .Permissiontitle:hover {
          color: #39a4ef;
        }
        .Content {
          width: 100%;
          margin-top: 10px;
          margin-left: 30px;
          .title {
            font-size: 15px;
            color: #c6cedb;
            margin-right: 25px;
          }
          .radio {
            width: 210px;
            // margin-right: 20px;
          }
          .select {
            display: inline-block;
            max-width: 260px;
          }
          .cangkuAction {
            display: flex;
            flex-flow: row;
            justify-content: flex-start;
            align-items: center;
          }
        }
      }
    }
  }
}
</style>
